#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 22 19:58:20 2017

@author: bianzhangxing
"""
import numpy as np
import cv2
import matplotlib.pyplot as plt 
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Waitforsbbzx(QThread):
    def _init_(self):
        super(Waitforsbbzx, self).__init__()
        
    cap=None

    _endgenerating=pyqtSignal()

    def run(self):
        print "sb"
        alpha=0.9
        K=40
        #cap = cv2.VideoCapture("../fucing.avi" )
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
        fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows=True)
        # get the Video's information
        Numframes=int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
        fps = self.cap.get(cv2.CAP_PROP_FPS)  
        size = (int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)),   
                int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
        
        # construct the activity histogram
        Ha1=np.zeros(Numframes+1)
        count=0
        ret, frame = self.cap.read()
        #generate the the activity histogram
        while(1):
            ret, frame = self.cap.read()
            if ret==0:
                break
            count=count+1
            fgmask = fgbg.apply(frame)
            fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
            Ha1[count]=np.sum(fgmask==255)
        #    print Ha1[count]
        #    cv2.imshow('frame',fgmask)
        #    k = cv2.waitKey(1) & 0xff
        #    if k == 27:
        #        break
        
        #cv2.waitKey(1)
        #cv2.destroyAllWindows()
        #cv2.waitKey(1)
        
        x=np.arange(0,Numframes+1)
        Ha2=np.zeros(Numframes+1)
        Ha3=np.zeros(Numframes+1)
        mean=np.mean(Ha1)
        Ha2[:]=mean
        
        Ha3=alpha*Ha1+(1-alpha)*Ha2
        
        # exstrac the frames according to the area
        threshold=K*mean
        cnt_i=0
        cnt_sum=0
        extract=np.array([])
        for i in x:
            cnt_sum=cnt_sum+Ha3[i]
            if cnt_sum>threshold:
                cnt_sum=0
                extract=np.append(extract,i)#save the extracted frame's index
        #wirte video
        #videoWriter = cv2.VideoWriter('out.mp4', 
        #                              cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 
        #                              fps, size)  
        videoWriter = cv2.VideoWriter('out.avi', 
                                      cv2.VideoWriter_fourcc('P','I','M','1'), 
                                      int(fps), size) 
        if videoWriter.isOpened():
            for index in extract:
                self.cap.set(1,index)
                ret, frame = self.cap.read()
                cv2.waitKey(1000/int(fps)) #delay
                videoWriter.write(frame) #
        self.cap.release()
        self._endgenerating.emit()
        '''
        plt.figure(1)
        plt.plot(x,Ha1,'r',x,Ha2,'b',x,Ha3,'y')
        
        plt.figure(1)
        for index in extract:
            plt.plot([index,index],[0,Ha3[int(index)]],'k', linewidth=1, linestyle="-")
        '''
        print "end"

    





















